<?php
namespace app\admin\controller;
use app\admin\model\User as UserModel;
use app\admin\controller\Base;//权限验证
use think\Loader;
use think\Session;
class User extends Base{
	public function index(){
		$model= new UserModel();
		//会员分页
		$list = UserModel::paginate(5);
		$this->assign('list',$list);
		return $this->fetch('list');
	}
	public function add(){
		//会员添加
		if(request()->isPost()){
			//密码是否为空:为空则不加密,不为空则加密
			$password=input('password');
			if(empty($password)){
				$data=[
					'username'=>input('username'),
					'password'=>input('password'),
					'email'=>input('email'),
					'addtime'=>date("Y-m-d H:i:s"),
				];
			}else{
				$data=[
					'username'=>input('username'),
					'password'=>md5(sha1(input('password'))),
					'email'=>input('email'),
					'addtime'=>date("Y-m-d H:i:s"),
				];
			}
			
			$validate = Loader::validate('User');
			if(!$validate->scene('add')->check($data)){
				//场景验证
			   $this->error($validate->getError()); 
			   die();
			}
			if(db('user')->insert($data)){
				return $this->success('添加会员成功！','index');
			}else{
				return $this->error('添加会员失败！');
			}
			return;
		}
		return $this->fetch('add');
	}
	
	
	
	public function edit(){
		//会员修改
		$id=input('id');
		$users=db('user')->find($id);
		if(request()->isPost()){
			$data=[
				'id'=>input('id'),
				'username'=>input('username'),
				'email'=>input('email')
			];
			if(input('password')){
				$data['password']=md5(sha1(input('password')));
			}else{
				//如果没输入密码将原来的密码赋值到文本框
				$data['password']=$users['password'];
			}
			$validate = Loader::validate('User');//验证器
			if(!$validate->scene('edit')->check($data)){
				//验证场景
			   $this->error($validate->getError()); 
			   die();
			}
	        $save=db('user')->update($data);
			if($save !== false){
				$this->success('修改会员成功！','index');
			}else{
				$this->error('修改会员失败！');
			}
			return;
		}
		$this->assign('users',$users);
		return $this->fetch('edit');
	}
	
	public function state(){
		//管理员状态修改
		$state=input('state');
		$id=input('id');
		
		if($state == 1){
			if(db('user')->where('id',$id)->update(['state' => '0'])){
				$this->success('会员禁用成功！','index');
			}else{
				$this->error('会员禁用失败！');
			}
		}else{
			if(db('user')->where('id',input('id'))->update(['state' => '1'])){
				$this->success('会员启用成功！','index');
			}else{
				$this->error('会员启用失败！');
			}
		}
		
	}
	
	
	public function del(){
		//管理员删除
		$id=input('id');
		
		if(db('user')->delete(input('id'))){
			$this->success('会员删除成功！','index');
		}else{
			$this->error('会员删除失败！');
		}

	}
}